<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :span="8" :xs="24">
        <el-card class="profile-card">
          <div class="profile-header">
            <el-avatar :size="80" :src="userInfo.avatar || defaultAvatar" />
            <h3>{{ userInfo.username }}</h3>
            <p class="user-role">{{ getUserRoleText(userInfo.userType) }}</p>
          </div>
          
          <div class="profile-info">
            <ul class="info-list">
              <li>
                <el-icon><User /></el-icon>
                <span class="label">用户名:</span>
                <span class="value">{{ userInfo.username }}</span>
              </li>
              <li>
                <el-icon><Message /></el-icon>
                <span class="label">邮箱:</span>
                <span class="value">{{ userInfo.email || '未设置' }}</span>
              </li>
              <li>
                <el-icon><Phone /></el-icon>
                <span class="label">手机:</span>
                <span class="value">{{ userInfo.phone || '未设置' }}</span>
              </li>
              <li>
                <el-icon><Calendar /></el-icon>
                <span class="label">注册时间:</span>
                <span class="value">{{ formatDate(userInfo.createTime) }}</span>
              </li>
              <li>
                <el-icon><Clock /></el-icon>
                <span class="label">最后登录:</span>
                <span class="value">{{ userInfo.lastLoginTime ? formatDate(userInfo.lastLoginTime) : '首次登录' }}</span>
              </li>
            </ul>
          </div>
        </el-card>
        
        <!-- 统计信息卡片 -->
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span>个人统计</span>
            </div>
          </template>
          <div class="stats-content">
            <div class="stat-item">
              <div class="stat-icon" style="background-color: #409eff;">
                <el-icon color="white"><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.literatureCount }}</div>
                <div class="stat-label">上传文献</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon" style="background-color: #67c23a;">
                <el-icon color="white"><Star /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.favoriteCount }}</div>
                <div class="stat-label">收藏文献</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon" style="background-color: #e6a23c;">
                <el-icon color="white"><Search /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.searchCount }}</div>
                <div class="stat-label">搜索次数</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 编辑信息和活动记录 -->
      <el-col :span="16" :xs="24">
        <el-tabs v-model="activeTab" class="profile-tabs">
          <!-- 基本信息编辑 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-card class="edit-card">
              <template #header>
                <div class="card-header">
                  <span>编辑个人信息</span>
                </div>
              </template>
              <el-form 
                :model="editForm" 
                :rules="editRules" 
                ref="editFormRef" 
                label-width="100px"
              >
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="editForm.username" disabled />
                </el-form-item>
                <el-form-item label="真实姓名" prop="realName">
                  <el-input v-model="editForm.realName" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="editForm.email" />
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                  <el-input v-model="editForm.phone" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateProfile" :loading="updating">
                    保存修改
                  </el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>
          
          <!-- 修改密码 -->
          <el-tab-pane label="安全设置" name="security">
            <el-card class="security-card">
              <template #header>
                <div class="card-header">
                  <span>修改密码</span>
                </div>
              </template>
              <el-form 
                :model="passwordForm" 
                :rules="passwordRules" 
                ref="passwordFormRef" 
                label-width="100px"
              >
                <el-form-item label="当前密码" prop="oldPassword">
                  <el-input 
                    v-model="passwordForm.oldPassword" 
                    type="password" 
                    show-password 
                  />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input 
                    v-model="passwordForm.newPassword" 
                    type="password" 
                    show-password 
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input 
                    v-model="passwordForm.confirmPassword" 
                    type="password" 
                    show-password 
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="changePassword" :loading="changingPassword">
                    修改密码
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>
          
          <!-- 最近活动 -->
          <el-tab-pane label="最近活动" name="activity">
            <el-card class="activity-card">
              <template #header>
                <div class="card-header">
                  <span>最近活动记录</span>
                </div>
              </template>
              <div class="activity-list">
                <div 
                  v-for="(activity, index) in activities" 
                  :key="index" 
                  class="activity-item"
                >
                  <div class="activity-icon">
                    <el-icon :color="getActivityIconColor(activity.type)">
                      <component :is="getActivityIcon(activity.type)" />
                    </el-icon>
                  </div>
                  <div class="activity-content">
                    <div class="activity-title">{{ activity.title }}</div>
                    <div class="activity-desc">{{ activity.description }}</div>
                    <div class="activity-time">{{ formatTime(activity.time) }}</div>
                  </div>
                </div>
                <div v-if="activities.length === 0" class="empty-activities">
                  <el-empty description="暂无活动记录" :image-size="80" />
                </div>
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { 
  User, Message, Phone, Calendar, Clock, Document, Star, Search,
  Edit, Key, Ticket, Upload, Download, Delete, Plus
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { userApi } from '@/api/user'
import type { UserInfo } from '@/api/user'
import defaultAvatar from '@/assets/images/default-avatar.png?inline'

const router = useRouter()
const userStore = useUserStore()
const activeTab = ref('basic')
const updating = ref(false)
const changingPassword = ref(false)

const userInfo = ref<UserInfo>({
  id: 0,
  username: '',
  email: '',
  phone: '',
  realName: '',
  avatar: '',
  status: 1,
  userType: 1,
  lastLoginTime: '',
  createTime: ''
})

const stats = ref({
  literatureCount: 0,
  favoriteCount: 0,
  searchCount: 0
})

const activities = ref([
  {
    type: 'upload',
    title: '上传文献',
    description: '上传了文献《基于深度学习的医学图像分析》',
    time: '2023-05-15 14:30:22'
  },
  {
    type: 'favorite',
    title: '收藏文献',
    description: '收藏了文献《癌症免疫治疗新进展》',
    time: '2023-05-14 09:15:45'
  },
  {
    type: 'search',
    title: '文献搜索',
    description: '搜索了关键词"基因编辑"',
    time: '2023-05-13 16:42:18'
  },
  {
    type: 'login',
    title: '登录系统',
    description: '成功登录医学文献管理系统',
    time: '2023-05-12 08:20:33'
  }
])

const editForm = reactive({
  username: '',
  realName: '',
  email: '',
  phone: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const editFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 表单验证规则
const editRules = reactive<FormRules>({
  realName: [
    { required: false, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: false, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: false, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

const passwordRules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 方法
const loadUserInfo = async () => {
  try {
    const data: UserInfo = await userApi.getUserInfo()
    userInfo.value = data
    editForm.username = data.username
    editForm.realName = data.realName || ''
    editForm.email = data.email || ''
    editForm.phone = data.phone || ''
  } catch (error: any) {
    ElMessage.error(error.message || '获取用户信息失败')
  }
}

const updateProfile = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      updating.value = true
      try {
        // 构造更新数据对象，只包含需要更新的字段
        const updateData = {
          realName: editForm.realName,
          email: editForm.email,
          phone: editForm.phone
        }
        
        // 调用更新用户信息的API
        await userApi.updateUserInfo(updateData)
        ElMessage.success('个人信息更新成功')
        updating.value = false
        loadUserInfo()
      } catch (error: any) {
        ElMessage.error(error.message || '更新失败')
        updating.value = false
      }
    }
  })
}

const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      changingPassword.value = true
      try {
        // 调用修改密码的API
        await userApi.changePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        ElMessage.success('密码修改成功，请重新登录')
        changingPassword.value = false
        
        // 清空表单
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
        
        // 重新登录
        userStore.logout()
        router.push('/login')
      } catch (error: any) {
        ElMessage.error(error.message || '密码修改失败')
        changingPassword.value = false
      }
    }
  })
}

const resetForm = () => {
  editForm.realName = userInfo.value.realName || ''
  editForm.email = userInfo.value.email || ''
  editForm.phone = userInfo.value.phone || ''
}

const getUserRoleText = (userType: number) => {
  const roles: Record<number, string> = {
    1: '普通用户',
    2: '管理员'
  }
  return roles[userType] || '普通用户'
}

const getActivityIcon = (type: string) => {
  const icons: Record<string, any> = {
    upload: Upload,
    favorite: Star,
    search: Search,
    login: Ticket,
    download: Download,
    delete: Delete
  }
  return icons[type] || Edit
}

const getActivityIconColor = (type: string) => {
  const colors: Record<string, string> = {
    upload: '#409eff',
    favorite: '#67c23a',
    search: '#e6a23c',
    login: '#909399',
    download: '#409eff',
    delete: '#f56c6c'
  }
  return colors[type] || '#409eff'
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

const formatTime = (dateStr: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-card, .stats-card, .edit-card, .security-card, .activity-card {
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.profile-header {
  text-align: center;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.profile-header h3 {
  margin: 15px 0 5px 0;
  color: #303133;
}

.user-role {
  color: #909399;
  font-size: 14px;
}

.profile-info {
  padding: 20px 0;
}

.info-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.info-list li {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  transition: background-color 0.3s;
}

.info-list li:hover {
  background-color: #f5f7fa;
}

.info-list li .el-icon {
  margin-right: 10px;
  color: #409eff;
}

.label {
  flex: 0 0 80px;
  color: #909399;
  margin-right: 10px;
}

.value {
  flex: 1;
  color: #303133;
}

.card-header {
  font-weight: bold;
  color: #303133;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-content {
  padding: 20px 0;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  flex-shrink: 0;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 3px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.profile-tabs {
  border-radius: 10px;
  overflow: hidden;
}

.activity-list {
  max-height: 500px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  flex-shrink: 0;
}

.activity-content {
  flex: 1;
}

.activity-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.activity-desc {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}

.activity-time {
  color: #909399;
  font-size: 12px;
}

.empty-activities {
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }
  
  .el-col {
    margin-bottom: 20px;
  }
}
</style>